package net.service;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/**
 *
 * @author Dustin
 */
public class Server extends Thread implements Protocol {
    private int index;
    private boolean connected;
    private ServerSocket serverSocket;
    private ArrayList<ClientHandler> clients = new ArrayList<ClientHandler>();

    @Override
    public void run() {
        while(connected) {
            try {
                Socket s = serverSocket.accept();
                ClientHandler h = new ClientHandler(this, index++, s);
                addClient(h);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    public void sendMessage(int index, String message) {
        boolean hasFound = false;
        for(int i = 0; i < clients.size() && !hasFound; i++) {
            if(clients.get(i).getIndex() == index) {
                clients.get(i).sendMessage(message);
                hasFound = true;
            }
        }
        System.out.println("Sent to: " + index + " : " + message);
    }

    public void broadcast(String message) {
        for(ClientHandler h : clients) {
            h.sendMessage(message);
        }
        System.out.println("Broadcasted" + message);
    }

    public void connect(int port) {
        if(!connected) {
            try {
                serverSocket = new ServerSocket(port);
                connected = true;
                start();
                System.out.println("Server online");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void disconnect() {
        if(connected) {
            try {
                connected = false;
                serverSocket.close();
                System.out.println("Disconnected");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void addClient(ClientHandler h) {
        clients.add(h);
        System.out.println(h.getIndex() + " connected");
    }

    public void removeClient(ClientHandler h) {
        clients.remove(h);
        System.out.println(h.getIndex() + " disconnected");
    }
}
